package com.hcbd.tdwt.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;


import androidx.core.app.ActivityCompat;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.hcbd.tdwt.util.ConvertData;
import com.hcbd.tdwt.util.DateUtils;
import com.hcbd.tdwt.util.FileUtil;
import com.hcbd.tdwt.util.FileUtils;
import com.pancoit.compression.ZDCompression;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.ui.common.provider.PicProvider;
import com.hcbd.tdwt.ui.xingyu.vo.SendImgDataVO;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayDeque;
import java.util.List;

/**
 * 图片发送管理类
 *
 * **/
public class ImgSendManager {
    private final ArrayDeque<SendImgDataVO> queue;//图片字节队列
    private static ImgSendManager imgSendManager;
    private boolean isSend=false;//是否发送
    public int currentSize;//当前大小
    public int totalSeconds;//
    public SendImgDataVO currentSendImgDataVO;
    public UserMessageVO userMessage;
    public List<byte[]> pIcZipList;
    public static int delaySeconds=10;
    public String totalSize;
    /**
     * 单例获取该stack
     *
     * @return
     */
    public static synchronized ImgSendManager getInstance() {
        if (imgSendManager == null) {
            synchronized (ImgSendManager.class) {
                if (imgSendManager == null) {
                    imgSendManager = new ImgSendManager();
                }
            }
        }
        return imgSendManager;
    }
    private ImgSendManager(){
        queue=new ArrayDeque<>();
    }

    public void setSendByteList(UserMessageVO userMessage){
        if(pIcZipList==null||pIcZipList.size()==0){
            clear(Constant.SEND_MSG_FAIL);
            return;
        }
        this.currentSize=pIcZipList.size();
        this.totalSeconds=currentSize*(BeidouBoxParams.sendFreq+delaySeconds);
        this.totalSize=getByteListSize();
        String size= FileUtils.getFileMbSize(userMessage.getContent());
        for(int i=0;i<pIcZipList.size();i++){
            SendImgDataVO sendImgDataVO=new SendImgDataVO();
            sendImgDataVO.setId(i);
            sendImgDataVO.setContent(pIcZipList.get(i));
            sendImgDataVO.setCreateTime(DateUtils.dateToTimeStamp(userMessage.getSendTime(),""));
            sendImgDataVO.setPackageSize(pIcZipList.size());
            sendImgDataVO.setSendNumber(userMessage.getReceiverNumber());
            sendImgDataVO.setOldImgSize(size);
            queue.add(sendImgDataVO);
        }
        pIcZipList=null;
    }

    public void send(){
        currentSendImgDataVO=null;
        currentSendImgDataVO =queue.pollFirst();
        if(currentSendImgDataVO==null||!isSend||!BeidouBoxParams.isBoxConnectNormal){
            clear(Constant.SEND_MSG_FAIL);
            return;
        }
        //todo:s40575921
        final String bdMsg = castUserMessageTo0xA9(currentSendImgDataVO,GlobalParams.commandCentreNumber);
        BdToolFactory.getBdSendBase().sendMsg(currentSendImgDataVO.getSendNumber(),2,2,bdMsg);
  /*     new Thread(new Runnable() {
            @Override
            public void run() {
                UserMessageVO userMessageVO = ConvertToUserMsgTool.cast0xA9ToUserMessage(bdMsg,currentSendImgDataVO.getSendNumber());
            }
        }).start();*/
        if(queue.size()==0){
            clear(Constant.SEND_MSG_SUCCESS);
            if(sendPicCallback!=null){
                sendPicCallback.onFinish();
            }
        }
        MainApp.getInstance().startNewSentWaitSecTimer();
    }
    public String getByteListSize(){
        int byteStartLen=pIcZipList.get(0).length;
        int byteEndLen=pIcZipList.get(currentSize-1).length;
        int byteLen=(((currentSize-1)*byteStartLen)+byteEndLen);
        return byteToMB(byteLen);
    }
    //将字节数转化为MB
    @SuppressLint("DefaultLocale")
    private String byteToMB(long size){
        long kb = 1024;
        long mb = kb*1024;
        long gb = mb*1024;
        if (size >= gb){
            return String.format("%.1f GB",(float)size/gb);
        }else if (size >= mb){
            float f = (float) size/mb;
            return String.format(f > 100 ?"%.0f MB":"%.1f MB",f);
        }else if (size > kb){
            float f = (float) size / kb;
            return String.format(f>100?"%.0f KB":"%.1f KB",f);
        }else {
            return String.format("%d B",size);
        }
    }
    public boolean isSend() {
        return isSend;
    }

    public void setSend(boolean send) {
        isSend = send;
    }

    public void clear(int type){
        if(userMessage!=null){
            userMessage.setStatus(type);
            userMessage.update();
        }
        userMessage=null;
        isSend=false;
        pIcZipList=null;
        queue.clear();
        EventBus.getDefault().unregister(this);
    }
    public SendPicCallback sendPicCallback;
    public interface SendPicCallback {
        void  onFinish();
    }
    public void setSendPicCallback(SendPicCallback sendPicCallback){
        this.sendPicCallback=sendPicCallback;
    }

    @Subscribe(threadMode = ThreadMode.ASYNC, sticky = true, priority = 1)
    public void eventBus(Integer delaySeconds){
        if(isSend&&delaySeconds==0){
            if(isNewSend){
                newSendImg();
            }else{
                send();
            }
        }
    }

    public boolean checkPermissionOrOpenPermission(Activity activity){
        return checkPermission(activity,Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION);
    }
    /**
     * 判断系统版本大于6.0的时候
     *
     * @param permissions 申请权限

     */
    protected boolean checkPermission(Activity activity ,String... permissions) {
        //大于6.0的时候需要动态申请权限.小于6.0的时候如果用户手动关闭权限,程序即崩 需要做Try处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return checkSelfPermissions(activity,permissions);
        }
        return true;
    }
    /**
     * 检查权限是否已经授权
     *
     * @param permissions 申请权限
     * @return
     */
    public boolean checkSelfPermissions(Activity activity, String... permissions) {
        boolean flag = true;
        for (String p : permissions) {
            if (ActivityCompat.checkSelfPermission(activity, p) != PackageManager.PERMISSION_GRANTED) {
                flag = false;
                break;
            }
        }
        return flag;
    }
    public void selectImg(Activity activity,final int cameraCode,final String cameraFilePath,final int  photoAlbum){
        final Dialog mShareDialog = new Dialog(activity, R.style.dialog_bottom_full);
        mShareDialog.setCanceledOnTouchOutside(true);
        mShareDialog.setCancelable(true);
        Window window = mShareDialog.getWindow();
        assert window != null;
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.share_animation);
        View view = View.inflate(activity, R.layout.picture_selection_diaolg, null);
        view.findViewById(R.id.photoAlbum).setOnClickListener(view12 -> {
            startAlbum(activity,photoAlbum);
            mShareDialog.dismiss();
        });
        view.findViewById(R.id.camera).setOnClickListener(view1 -> {
            camera(activity,cameraCode,cameraFilePath);
            mShareDialog.dismiss();
        });
        window.setContentView(view);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        mShareDialog.show();
    }
    public void camera(Activity activity,int code,String temporaryPictureFilesJPG) {

        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            takePhotoBiggerThan7(activity,(new File(temporaryPictureFilesJPG)).getAbsolutePath(),code);
        }else {
            // 指定拍照意图
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // 加载路径图片路径
            Uri mUri = Uri.fromFile(new File(temporaryPictureFilesJPG));
            // 指定存储路径，这样就可以保存原图了
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
            if (intent.resolveActivity(activity.getPackageManager()) != null) {
                activity.startActivityForResult(intent, code);
            }
        }
    }
    public void takePhotoBiggerThan7(Activity activity,String absolutePath,int code) {
        try {
            ContentValues values = new ContentValues(1);
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
            values.put(MediaStore.Images.Media.DATA, absolutePath);
            Uri photoURI = null;
            try {
                photoURI = PicProvider.getUriForFile(activity.getApplicationContext(), "hcbd.PicProvider",new File(absolutePath));
            }catch (Exception e){
                e.printStackTrace();
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (photoURI != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            }
            activity.startActivityForResult(intent, code);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void startAlbum(Activity activity,int code) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        activity.startActivityForResult(intent, code);
    }
    public void selectImg(Activity activity){
        if(!AuthManger.getAuthManger().isPicOnline()) {
            String str= ZDCompression.getInstance().getImgOffInfo();
            if ("".equals(str) || str == null) {
                MainApp.getInstance().showMsg("图片库未初始化,无法使用!");
                return;
            }
            String[] array = str.split(",");
            int usageCount=Integer.parseInt(array[0]);
            String endDate=array[2];
            String currentDate=DateUtils.getDateLongSerial();
            int code= DateUtils.dataContrast(currentDate, endDate);
            if (code==-1||code==0||0>=usageCount) {
                MainApp.getInstance().showMsg("库已过期,请授权");
                return;
            }
            if(BeidouBoxParams.card_model==2){
                MainApp.getInstance().showMsg("二代卡无法发送图片!");
                return;
            }
        }
        if(4>BeidouBoxParams.cardType){
            MainApp.getInstance().showMsg("发送图片请选择四级及以上的卡！");
            return;
        }
        if(checkPermissionOrOpenPermission(activity)){
            cameraPath = FileUtil.getTemporaryPictureFilesJPG();
            selectImg(activity,CAMERA,cameraPath,SELECT_PICK_CODE);
        }else{
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.CAMERA,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,}, 1088);
        }
    }
    public  String castUserMessageTo0xA9(SendImgDataVO sendImgDataVO,String str) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0xA9 1个字节
        byte requestHeaderByte = (byte) 0xA9;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //接收者电话号码5个字节
        byte[] phoneBytes = ConvertData.long2bytes(Long.parseLong(str, 10));
        hex.append(ConvertData.bytes2hex(phoneBytes).substring(6));
        hex.append(ConvertData.longToHex(Long.parseLong(sendImgDataVO.getCreateTime())).substring(8));
        //总包数量
        hex.append(ConvertData.toLength(String.format("%x",sendImgDataVO.getPackageSize()), 2));
        //当前包序号
        hex.append(ConvertData.toLength(String.format("%x", sendImgDataVO.getId()), 2));
        try {
            String content=ConvertData.bytes2hex(sendImgDataVO.getContent());
            hex.append(content);
        } catch (Exception e){
            e.printStackTrace();
        }
        return hex.toString().toUpperCase();
    }
    public static String cameraPath;
    public static final int SELECT_PICK_CODE=20;
    public static final int  PICK_PIC=13;
    public static final int CAMERA = 14;
    public String castUserMessageTo0xAA(SendImgDataVO sendImgDataVO,String str) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0xA9 1个字节
        byte requestHeaderByte = (byte) 0xAA;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //接收者电话号码5个字节
        byte[] phoneBytes = ConvertData.long2bytes(Long.parseLong(str, 10));
        hex.append(ConvertData.bytes2hex(phoneBytes).substring(6));

        hex.append(ConvertData.longToHex(Long.parseLong(sendImgDataVO.getCreateTime())).substring(8));
        String oldImgSize=sendImgDataVO.getOldImgSize().trim();
        String oldSize=oldImgSize.replace(".","");
        hex.append(ConvertData.toLength(ConvertData.intToHex(Integer.parseInt(oldSize)),6));
        //总包数量
        hex.append(ConvertData.toLength(String.format("%x",sendImgDataVO.getPackageSize()), 2));
        //当前包序号
        hex.append(ConvertData.toLength(String.format("%x", sendImgDataVO.getId()), 2));
        try {
            String content=ConvertData.bytes2hex(sendImgDataVO.getContent());
            hex.append(content);
        } catch (Exception e){
            e.printStackTrace();
        }

        return hex.toString().toUpperCase();
    }
    public void newSendImg(){
        currentSendImgDataVO=null;
        currentSendImgDataVO =queue.pollFirst();
        if(currentSendImgDataVO==null||!isSend||!BeidouBoxParams.isBoxConnectNormal){
            clear(Constant.SEND_MSG_FAIL);
            return;
        }
        String bdMsg = castUserMessageTo0xAA(currentSendImgDataVO,GlobalParams.commandCentreNumber);
        BdToolFactory.getBdSendBase().sendMsg(GlobalParams.rdCentreNumber,2,2,bdMsg);
        if(queue.size()==0){
            clear(Constant.SEND_MSG_SUCCESS);
            if(sendPicCallback!=null){
                sendPicCallback.onFinish();
            }
        }
        MainApp.getInstance().startNewSentWaitSecTimer();
    }
    private boolean isNewSend=false;
    public void sendImg(UserMessageVO userMessage){
        this.userMessage=userMessage;
        setSend(true);
        EventBus.getDefault().register(this);
        setSendByteList(userMessage);
        send();
    }
    public void newSendImg(UserMessageVO userMessage){
        this.userMessage=userMessage;
        isNewSend=true;
        EventBus.getDefault().register(this);
        setSend(true);
        setSendByteList(userMessage);
        newSendImg();
    }
}
